<template>
  <div>
    <a-table :pagination="false" :scroll="{ x: 1500 }" :columns="columns" :data-source="data" :row-key="(record) => record.code" class="components-table-demo-nested">
      <template #bodyCell="{ column, record, index }">
        <!-- 文件名称 -->
        <template v-if="column.dataIndex == 'name'">
          <div>
            <a-select
              :dropdownStyle="{ minHeight: '350px', minWidth: '350px' }"
              :style="[{ width: '100%' }, record.nameRequired ? { border: '1px solid red' } : {}]"
              v-model:value="record.name"
              show-search
              :filter-option="filterOption"
              @dropdownVisibleChange="launchName(record, index)"
              @blur="inputValueName(record)"
              placeholder="请选择"
            >
              <template #notFoundContent>
                <div><a-table :pagination="false" :scroll="{ y: 400 }" :dataSource="fileNameData" :columns="fileNameColumn" :customRow="rowClick" /></div>
              </template>
            </a-select>
            <span v-if="record.nameRequired" class="holder">请输入</span>
          </div>
        </template>

        <!-- 文件类型 -->
        <template v-if="column.dataIndex == 'directoryId'">
          <div>
            <a-tree-select
              :bordered="false"
              v-model:value="record.directoryId"
              :disabled="true"
              :field-names="{ label: 'name', value: 'id', children: 'children' }"
              tree-default-expand-all
              :tree-data="treeDataType"
              tree-node-filter-prop="name"
            >
            </a-tree-select>
          </div>
        </template>

        <!-- 文件负责人 -->
        <template v-if="column.dataIndex == 'principalId'">
          <div>
            <a-select
              :bordered="false"
              :disabled="true"
              v-model:value="record.principalId"
              :options="subjectOptions"
              :field-names="{
                label: 'nickName',
                value: 'id'
              }"
            />
          </div>
        </template>

        <!-- 文件会签人 -->
        <!-- <template v-if="column.dataIndex == 'counterSignIds'">
          <div>
            <a-select
              :bordered="false"
              :disabled="true"
              v-model:value="record.counterSignIds"
              :options="subjectOptions"
              mode="multiple"
              :field-names="{
                label: 'nickName',
                value: 'id'
              }"
            />
          </div>
        </template> -->

        <!-- 保密等级 -->
        <!-- <template v-if="column.dataIndex == 'securityLevel'">
          <div>
            <a-cascader :bordered="false" :disabled="true" v-model:value="record.securityLevel" :options="LevelOptions" style="width: 80px" />
          </div>
        </template> -->

        <!-- 是否文件模板 -->
        <template v-if="column.dataIndex == 'isTemplate'">
          <div>
            <a-cascader :bordered="false" :disabled="true" v-model:value="record.isTemplate" :options="templateOptions" style="width: 80px" />
          </div>
        </template>

        <!-- 申请原因 -->
        <template v-if="column.dataIndex == 'applyReason'">
          <div>
            <a-input v-model:value="record.applyReason" />
          </div>
        </template>
        <!-- 删除项 -->
        <template v-else-if="column.key === 'operation'">
          <span @click="onDelete(record.code)" class="form-table-actions">删除</span>
        </template>
      </template>
      <!-- 必填选项 -->
      <template #headerCell="{ column }"
        ><template v-if="column.key === 'name'"><span class="form-table-heard">文件名称</span></template>
        <!-- <template v-else-if="column.key === 'securityLevel'"
          ><span class="">保密等级 </span>
          <a-tooltip placement="top" :overlayStyle="{ maxWidth: '655px' }">
            <template #title>
              <p>
                <span>1、绝密：指一旦泄密会使国家遭受严重危害和重大损失的。特指某些秘密文件资料，比如设计图纸、</span>
              </p>
              <p>
                <span>投标方案、电子帐本、程序源码、个人隐私以及一些包含重要信息的录像带和光盘等文件。</span>
              </p>
              <p>
                <span>2、机密：指标有“机密”密级的文件、简报等形式含有国家重要秘密、泄露会使国家的安全和利益</span>
              </p>
              <p>
                <span>遭受严重的损害的载体。有文件、简报、讲话材料，各种资料、报表、刊物，以文字、符号、图形、</span>
              </p>
              <p>
                <span>声、像等形式。</span>
              </p>
              <p>
                <span>3、秘密：可以称为私有文件，或者是因为某些原因，而不可以向大众公开的文件，如国家机密文件等。</span>
              </p>
              <p>
                <span>4、公开：没有什么影响，可以公开的。</span>
              </p>
            </template>
            <span class="promptIcon"><question-circle-outlined /></span>
          </a-tooltip>
        </template> -->
        <template v-else-if="column.key === 'applyReason'"><span>申请原因</span></template>
      </template>
    </a-table>
    <a-button type="dashed" @click="handleAdd" style="width: 100%">+ 添加</a-button>
  </div>
</template>

<script setup lang="ts">
import type { TreeSelectProps, CascaderProps } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { onBeforeUnmount, defineComponent, ref, computed, createVNode, getCurrentInstance, UnwrapRef, reactive, watch, inject, nextTick } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import { fileTree, findCanUseTree } from '@/config/api/publicFile';
import { fileByName, treeDataSubject, fileGet } from '@/config/api/documentApplication';

const route: any = useRoute();
const emit = defineEmits(['voidData']);
const newArr = ref([]);

// 初始化赋值
getViewData();
function getViewData() {
  if (['EDIT'].includes(route.query.showType)) {
    Promise.all([
      fileGet(route.query.id),
      findCanUseTree({}),
      treeDataSubject({
        parentId: 0
      })
    ]).then(([fileGetRes, fileTreeRes, treeDataSubjectRes]) => {
      const result = fileGetRes.data?.applyLists;
      data.value = result;
      getFileTree(fileTreeRes);
      getSubjectTree(treeDataSubjectRes);
      nextTick(() => {
        emit('voidData', data.value);
      });
    });
  } else {
    Promise.all([
      findCanUseTree({}),
      treeDataSubject({
        parentId: 0
      })
    ]).then(([fileTreeRes, treeDataSubjectRes]) => {
      getFileTree(fileTreeRes);
      getSubjectTree(treeDataSubjectRes);
    });
  }
}
const fileNameData = ref([]);
const fileNameColumn = [
  { title: '文件名称', dataIndex: 'name', key: 'name', width: 30, align: 'center' },
  { title: '编码', dataIndex: 'code', key: 'code', width: 30, align: 'center' }
];

async function launchName(record, index) {
  const params = { name: '' };
  const result = await fileByName(params);
  fileNameData.value = result.data;
  fileNameData.value.forEach((item) => {
    item.sum = index;
  });
}

const filterOption = (valueName: string, fileNameData: any) => {
  console.log(valueName);
  return fileNameData.name.toLowerCase().indexOf(valueName.toLowerCase()) >= 0;
};

function rowClick(record) {
  return {
    onClick: () => {
      newArr.value = [];
      // record.counterSignIds = filterData(record?.countersignResps);
      record.fileId = record.id;
      record.isShowIcon = false;
      Reflect.deleteProperty(record, 'id');
      data.value[record.sum] = record;
    }
  };
}

function filterData(arr) {
  arr?.forEach((item) => {
    newArr.value.push(item.countersignId);
  });
  return newArr.value;
}

const inputValueName = (record) => {
  record.nameRequired = false;
  if (record.name === undefined || record.name === '') {
    record.nameRequired = true;
    message.warning('此为必填项');
    return;
  }
};

// 文件类型树状
const treeDataType = ref<TreeSelectProps['treeData']>([]);
function getFileTree(result) {
  if (result.success) {
    treeDataType.value = result.data;
  }
}
// 文件负责 会签人
const subjectOptions = ref<CascaderProps['options']>([]);
function getSubjectTree(result) {
  if (result.success) {
    subjectOptions.value = result.data;
  }
}

// const inputValueApplyReason = (record) => {
//   record.applyReasonRequired = false;
//   if (record.applyReason === '') {
//     record.applyReasonRequired = true;
//     message.warning('此为必填项');
//     return;
//   }
//   console.log('一行数据', record);
//   console.log('总数据', data.value);
// };

// 保密等级
// const LevelOptions: CascaderProps['options'] = [
//   {
//     label: '公开',
//     value: 4
//   },
//   {
//     label: '机密',
//     value: 2
//   },
//   {
//     label: '绝密',
//     value: 1
//   },
//   {
//     label: '秘密',
//     value: 3
//   }
// ];

// 是否文件模板
const templateOptions: CascaderProps['options'] = [
  {
    label: '是',
    value: 1
  },
  {
    label: '否',
    value: 0
  }
];

const columns = [
  { title: '序号', dataIndex: 'index', key: 'index', width: 80, defaultSortOrder: 'descend', customRender: ({ index }) => index + 1 },
  { title: '文件名称', dataIndex: 'name', key: 'name', width: 120 },
  { title: '文件编码', dataIndex: 'code', key: 'code', width: 120 },
  { title: '文件类型', dataIndex: 'directoryId', key: 'directoryId', width: 150 },
  { title: '版本号', dataIndex: 'version', key: 'version', width: 100 },
  // { title: '保密等级', dataIndex: 'securityLevel', key: 'securityLevel', width: 140 },
  { title: '是否文件模板', dataIndex: 'isTemplate', key: 'isTemplate', width: 150 },
  { title: '文件负责人', dataIndex: 'principalId', key: 'principalId', width: 200 },
  // { title: '文件会签人', dataIndex: 'counterSignIds', key: 'counterSignIds', width: 150 },
  { title: '关键字', dataIndex: 'keyword', key: 'keyword', width: 150 },
  { title: '主要内容', dataIndex: 'mainContent', key: 'mainContent', width: 150 },
  { title: '申请原因', dataIndex: 'applyReason', key: 'applyReason', width: 150 },
  { title: '操作', key: 'operation', width: 180, fixed: 'right' }
];

const data: any = ref([]);
const handleAdd = () => {
  data.value.push({
    name: '',
    applyReason: '',
    nameRequired: false,
    applyReasonRequired: false
  });
};

// 主表删除项
const onDelete = (code) => {
  Modal.confirm({
    title: '是否确定删除',
    autoFocusButton: null,
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认',
    cancelText: '取消',
    onOk() {
      data.value = data.value.filter((item) => item.code !== code);
    }
  });
};

nextTick(() => {
  emit('voidData', data.value);
});
</script>
<style lang="less" scoped>
.form-table-heard:before {
  content: '*';
  color: #ff4d4f;
}
.form-table-actions {
  color: #005aea;
  cursor: pointer;
  margin-right: 10px;
}
.promptIcon {
  cursor: pointer;
  color: #005aea;
}
.color {
  border-color: red;
}
.holder {
  color: red;
}
/deep/ .ant-select-selection-item {
  color: #000 !important;
}
/deep/ .ant-select-arrow {
  display: none;
}
/deep/ .ant-select-selection-item {
  border-color: #fff !important;
}
</style>
